package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.OrderBean;
import com.project.bean.UserBean;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private IOrderService service;

    @RequestMapping("add")
    public String add(@Valid OrderBean order, BindingResult result,
                      HttpServletRequest request) throws Exception {
        if(result.hasErrors()){//判断是否有出错信息
            //取出出错信息集合
            List<FieldError> errorList = result.getFieldErrors();
            String str = new ObjectMapper().writeValueAsString(errorList);
            return str;
        }

        UserBean user = (UserBean)request.getSession()
                .getAttribute("loginUser");
        service.add(order,user.getId());
        return "ok";
    }
}
